import json


from django.db.models import F
from django.forms import model_to_dict


from django import forms
from django.http import JsonResponse
from django.shortcuts import render
from app01 import models
from app01.utils.bootstrap import BootstrapModelForm

from app01.utils.pagination import pagination


class CustomerModelForm(BootstrapModelForm):
    class Meta:
        model = models.CustomerList
        fields = '__all__'
        # exclude = ['oid', 'admin']

    def clean_customer_relationship_state(self):
        """清洗数据"""
        customer_relationship_state = self.cleaned_data.get('customer_relationship_state')
        return customer_relationship_state

    def clean_oid(self):
        """客户编号查重"""
        oid = self.cleaned_data.get('oid')
        if models.CustomerList.objects.filter(oid=oid).exists():
            raise forms.ValidationError('客户编号已存在')
        return oid

    def clean_name(self):
        """清洗数据"""
        customer_name = self.cleaned_data.get('name')
        return customer_name

    def clean_staff(self):
        """清洗数据"""
        staff = self.cleaned_data.get('staff')
        print('staff', staff)
        if staff == '0':
            raise forms.ValidationError('请选择负责人')
        return staff


def customer_list(request):
    queryset = models.CustomerList.objects.all().order_by('id')
    page_obj = pagination(request, queryset)
    form = CustomerModelForm()
    context = {
        'form': form,
        'queryset': page_obj.page_queryset,  # 分页后的数据
        'page_string': page_obj.html(),  # 生成页码
    }

    return render(request, 'customer_list_vue.html', context)


def customer_list_clean(customer_data):
    # 处理数据
    for i in customer_data:
        i['gender'] = models.CustomerList.gender_choices[int(i['gender']) - 1][1]

        i['deposit_amount'] = models.CustomerList.deposit_amount_choice[int(i['deposit_amount']) - 1][1]
        i['customer_relationship_type'] = \
            models.CustomerList.customer_relationship_type_choice[int(i['customer_relationship_type']) - 1][1]

        i['customer_relationship_state_id'] = models.RelationshipState.objects.filter(
            id=i['customer_relationship_state_id']).first().name
        # 如果i['financial_product']是True，就返回是，否则返回否

        i['financial_product'] = '是' if i['financial_product'] else '否'
        i['fund_products'] = '是' if i['fund_products'] else '否'
        i['investment_assets'] = '是' if i['investment_assets'] else '否'
        i['add_weChat'] = '是' if i['add_weChat'] else '否'
        i['contract_stock'] = '是' if i['contract_stock'] else '否'
        i['yield_enhanced_products'] = '是' if i['yield_enhanced_products'] else '否'
        i['equity_public_offering'] = '是' if i['equity_public_offering'] else '否'
        i['small_t_one_assets'] = '是' if i['small_t_one_assets'] else '否'
        i['stock_financing'] = '是' if i['stock_financing'] else '否'
        i['more_t_one_assets'] = '是' if i['more_t_one_assets'] else '否'
        i['Private_equity_products'] = '是' if i['Private_equity_products'] else '否'
        i['configure_China'] = '是' if i['configure_China'] else '否'
        i['is_delete'] = '是' if i['is_delete'] else '否'
        i['create_time'] = i['create_time'].strftime('%Y-%m-%d')
        i['update_time'] = i['update_time'].strftime('%Y-%m-%d')
        if i['staff_id']:
            i['staff_id'] = models.StaffInfo.objects.filter(id=i['staff_id']).first().name
        else:
            i['staff_id'] = ''


def customer_post(request):
    """返回数据"""
    form = CustomerModelForm()
    if request.method == 'GET':
        #获取axios中Get请求附带的params


        user_num = request.tracer.user.get('id')
        print('user_num', user_num)
        # 获取登录者的用户id
        user_id = models.StaffInfo.objects.filter(staff_num=user_num).first().id
        print('user_id', user_id)
        # 获取登录者的用户级别
        user_level = models.StaffInfo.objects.filter(staff_num=user_num).first().level
        print('user_level', user_level)
        if user_level == 3:
            # 如果是管理员，就返回所有数据
            customer_data = models.CustomerList.objects.filter(is_delete=0).all().order_by('-staff__level').values()
        else:
            customer_data = models.CustomerList.objects.filter(is_delete=0, staff__staff_num=user_num).all().order_by(
                'id')

        customer_data = list(customer_data.values())
        # print('customer_data', customer_data)
        customer_list_clean(customer_data)

        customer_count = len(customer_data)

        # 获取资产量的选择
        deposit_amount_choice = models.CustomerList.deposit_amount_choice
        # 将deposit_amount_choice转换为[{'id': 1, 'name': '电话拒听的客户'},]
        deposit_amount_choice = [{'id': i[0], 'name': i[1]} for i in deposit_amount_choice]

        customer_relationship_type_choice = models.CustomerList.customer_relationship_type_choice

        # 将customer_relationship_type_choice转换为[{'id': 1, 'name': '电话拒听的客户'},]
        customer_relationship_type_choice = [{'id': i[0], 'name': i[1]} for i in customer_relationship_type_choice]

        customer_relationship_state_choice = models.RelationshipState.objects.all().order_by('id')
        customer_relationship_state_choice = list(customer_relationship_state_choice.values())

        staff_lis_choice = models.StaffInfo.objects.all().order_by('id')
        staff_lis_choice = list(staff_lis_choice.values())

        res_choice = {
            'deposit_amount_choice': deposit_amount_choice,
            'customer_relationship_type_choice': customer_relationship_type_choice,
            'customer_relationship_state_choice': customer_relationship_state_choice,
            'staff_lis_choice': staff_lis_choice
        }

        # print('customer_data', customer_data)
        return JsonResponse({'status': True, 'customer_data': customer_data, 'customer_count': customer_count,
                             'res_choice': res_choice, 'user_num': user_num})
    else:
        form = CustomerModelForm(request.POST)
        # 拿到报错
        print(form.errors)
        user_num = request.tracer.user.get('id')
        # Staff表中customer_count字段+1
        add_judge = models.StaffInfo.objects.filter(staff_num=user_num).update(customer_count=F('customer_count') + 1)
        print('add_judge', add_judge)
        # 查找客户姓名查重
        # customer_name =form.data.get('name')
        # customer_name_count = models.CustomerList.objects.filter(name=customer_name).count()
        # if customer_name_count:
        #     return JsonResponse({'status': False, 'errors': '客户姓名已存在'})

        if form.is_valid():
            form.save()
            return JsonResponse({'status': True})
        else:
            return JsonResponse({'status': False, 'errors': form.errors})


def customer_delete_list_clean(i):
    # 处理数据

    i['gender'] = models.CustomerList.gender_choices[int(i['gender']) - 1][1]

    i['deposit_amount'] = models.CustomerList.deposit_amount_choice[int(i['deposit_amount']) - 1][1]
    i['customer_relationship_type'] = \
        models.CustomerList.customer_relationship_type_choice[int(i['customer_relationship_type']) - 1][1]

    i['customer_relationship_state'] = models.RelationshipState.objects.filter(
        id=i['customer_relationship_state']).first().name
    # 如果i['financial_product']是True，就返回是，否则返回否

    i['financial_product'] = '是' if i['financial_product'] else '否'
    i['fund_products'] = '是' if i['fund_products'] else '否'
    i['investment_assets'] = '是' if i['investment_assets'] else '否'
    i['add_weChat'] = '是' if i['add_weChat'] else '否'
    i['contract_stock'] = '是' if i['contract_stock'] else '否'
    i['yield_enhanced_products'] = '是' if i['yield_enhanced_products'] else '否'
    i['equity_public_offering'] = '是' if i['equity_public_offering'] else '否'
    i['small_t_one_assets'] = '是' if i['small_t_one_assets'] else '否'
    i['stock_financing'] = '是' if i['stock_financing'] else '否'
    i['more_t_one_assets'] = '是' if i['more_t_one_assets'] else '否'
    i['Private_equity_products'] = '是' if i['Private_equity_products'] else '否'
    i['configure_China'] = '是' if i['configure_China'] else '否'
    i['is_delete'] = '是' if i['is_delete'] else '否'
    i['staff'] = models.StaffInfo.objects.filter(id=i['staff']).first().name


def customer_delete(request):
    """删除数据"""
    if request.method == 'POST':
        customer_msg = request.body.decode('utf-8')
        # b'{"id":"201"}'
        customer_id = eval(customer_msg).get('id')


        #由customer_id获取负责人的id
        staff_id = models.CustomerList.objects.filter(oid=customer_id).first().staff_id

        if not staff_id:
            admin_id = models.StaffInfo.objects.filter(staff_num='187377').first().id
            #直接删除，将is_delete字段设置为1，以及将staff_id设置为admin_id
            judege=models.CustomerList.objects.filter(oid=customer_id).update(is_delete=1,staff_id=admin_id)
            #修改admin_id的客户数量
            models.StaffInfo.objects.filter(id=admin_id).update(customer_count=F('customer_count') + 1)

            if judege:
                return JsonResponse({'status': True, 'msg': '由于无法找到负责人，已将客户分配给公共管理员'+models.StaffInfo.objects.filter(id=admin_id).first().name})
            else:
                return JsonResponse({'status': False})

        #由staff_id获取负责人的staff_num
        staff_num = models.StaffInfo.objects.filter(id=staff_id).first().staff_num


        print('staff_id',staff_id)
        print('customer_id', customer_id)
        # 获取该客户的所有数据

        customer_basic_data = models.CustomerList.objects.filter(oid=customer_id).first()
        print('customer_basic_data', customer_basic_data)
        # 处理该数
        if not customer_basic_data:
            return JsonResponse({'status': False, 'errors': '该客户不存在'})
        customer_basic_data = model_to_dict(customer_basic_data)
        print('customer_basic_data', customer_basic_data)
        customer_delete_list_clean(customer_basic_data)
        # 处理数据，删除前7个字段
        customer_basic_data.pop('id')
        customer_basic_data.pop('oid')
        customer_basic_data.pop('name')
        customer_basic_data.pop('gender')
        customer_basic_data.pop('deposit_amount')
        customer_basic_data.pop('customer_relationship_type')
        customer_basic_data.pop('customer_relationship_state')
        customer_basic_data.pop('is_delete')
        customer_basic_data.pop('staff')

        # 将每个字段名拼接'_count'
        customer_basic_data_count = {}
        for k, v in customer_basic_data.items():
            customer_basic_data_count[k + '_count'] = v
        print('customer_basic_data_count', customer_basic_data_count)

        # 如果customer_basic_data_count中的值是'是'，则Staff表中对应字-1，否则不变
        for k, v in customer_basic_data_count.items():
            if v == '是':
                judge=models.StaffInfo.objects.filter(staff_num=staff_num).update(**{k: F(k) - 1})

        #
        # Staff表中customer_count字段-1

        add_judge = models.StaffInfo.objects.filter(staff_num=staff_num).update(customer_count=F('customer_count') - 1)

        # 将CustomerList表中的is_delete字段改为1
        judge_delete = models.CustomerList.objects.filter(oid=customer_id).update(is_delete=1)
        if not judge_delete:
            return JsonResponse({'status': False, 'errors': '删除失败'})

        return JsonResponse({'status': True, 'msg': '删除成功'})
    else:
        return JsonResponse({'status': False})


def clean_deposit_amount_choice(deposit_amount_choice_string):
    # 判断deposit_amount_choice_string是否在deposit_amount_choice中
    deposit_amount_choice = models.CustomerList.deposit_amount_choice
    deposit_amount_choice = [{'id': i[0], 'name': i[1]} for i in deposit_amount_choice]

    for i in deposit_amount_choice:
        if deposit_amount_choice_string == i['name']:

            return i['id']
    return 1


def clean_customer_relationship_type(customer_relationship_type_string):
    # 判断customer_relationship_type_string是否在customer_relationship_type中
    customer_relationship_type_choice = models.CustomerList.customer_relationship_type_choice
    for i in customer_relationship_type_choice:
        if customer_relationship_type_string == i[1]:
            return i[0]
    return 0


# 处理数据
def edit_clean(customer_data):
    # 处理数据

    for i in customer_data:
        # 如果gender是男，就返回1，否则返回2
        i['gender'] = 1 if i['gender'] == '男' else 2
        # deposit_amount_choice查找选项中30万——50万是否存在列表，存在则返回下标

        i['deposit_amount'] = clean_deposit_amount_choice(i['deposit_amount'])
        i['customer_relationship_type'] = clean_customer_relationship_type(i['customer_relationship_type'])

        if isinstance(i['customer_relationship_state_id'], int):
            i['customer_relationship_state_id'] = models.RelationshipState.objects.filter(
                id=i['customer_relationship_state_id']).first().id
        else:
            i['customer_relationship_state_id'] = models.RelationshipState.objects.filter(
                name=i['customer_relationship_state_id']).first().id
        # 如果i['financial_product']为是则返回1，否则返回0
        i['financial_product'] = 1 if i['financial_product'] == '是' else 0
        i['fund_products'] = 1 if i['fund_products'] == '是' else 0
        i['investment_assets'] = 1 if i['investment_assets'] == '是' else 0
        i['add_weChat'] = 1 if i['add_weChat'] == '是' else 0
        i['contract_stock'] = 1 if i['contract_stock'] == '是' else 0
        i['yield_enhanced_products'] = 1 if i['yield_enhanced_products'] == '是' else 0
        i['equity_public_offering'] = 1 if i['equity_public_offering'] == '是' else 0
        i['small_t_one_assets'] = 1 if i['small_t_one_assets'] == '是' else 0
        i['stock_financing'] = 1 if i['stock_financing'] == '是' else 0
        i['more_t_one_assets'] = 1 if i['more_t_one_assets'] == '是' else 0
        i['Private_equity_products'] = 1 if i['Private_equity_products'] == '是' else 0
        i['configure_China'] = 1 if i['configure_China'] == '是' else 0
        i['is_delete'] = 1 if i['is_delete'] == '是' else 0
        # 如果i['staff_id']为数字，则返回i['staff_id']，否则返回0
        if isinstance(i['staff_id'], int):
            i['staff_id'] = models.StaffInfo.objects.filter(id=i['staff_id']).first().id
        else:
            i['staff_id'] = models.StaffInfo.objects.filter(name=i['staff_id']).first().id


def customer_edit(request):
    """编辑数据"""
    res = {
        'status': True,
        'message': '修改信息成功'
    }
    if request.method == 'POST':
        customer_message = request.body.decode('utf-8')
        customer_message = json.loads(customer_message)
        customer_message = list(customer_message.values())

        #获取customer_message中的staff_id
        staff_name = customer_message[0]['staff_id']
        print('staff_name',staff_name)
        #获取该名字对应的staff_num
        staff_num = models.StaffInfo.objects.filter(name=staff_name).first().staff_num



        user = models.StaffInfo.objects.filter(staff_num=staff_num).first()

        # 修改里边的staff_id
        for i in customer_message:
            i['staff_id'] = user.id
        edit_clean(customer_message)

        # 修改数据
        staff_id = customer_message[0]['staff_id']
        # 客户id
        customer_id = customer_message[0]['id']

        staff_work_data_list = customer_message[0].copy()
        # 添加数据
        # 处理数据，删除前六个字段
        staff_work_data_list.pop('id')
        staff_work_data_list.pop('oid')
        staff_work_data_list.pop('name')
        staff_work_data_list.pop('gender')
        staff_work_data_list.pop('deposit_amount')
        staff_work_data_list.pop('customer_relationship_type')
        staff_work_data_list.pop('customer_relationship_state_id')
        staff_work_data_list.pop('is_delete')
        staff_work_data_list.pop('staff_id')
        staff_work_data_list.pop('create_time')
        staff_work_data_list.pop('update_time')
        staff_work_data_list.pop('remark')


        # 获取staff_work_data_list中的key
        staff_work_data_list_key = list(staff_work_data_list.keys())


        # 获取客户表中对应字段的数据
        customer_basic_data = models.CustomerList.objects.filter(id=customer_id).values(*staff_work_data_list_key)


        customer_basic_data = customer_basic_data[0]

        # 将字段值为True的转换为1，False的转换为0
        for i in customer_basic_data:
            if customer_basic_data[i] == True:
                customer_basic_data[i] = 1
            elif customer_basic_data[i] == False:
                customer_basic_data[i] = 0


        temp_staff_key = staff_work_data_list_key.copy()

        # 将temp_staff_key+'_count'
        for i in temp_staff_key:
            temp_staff_key[temp_staff_key.index(i)] = i + '_count'

        # 获取员工表中对应字段的数据
        staff_basic_data = models.StaffInfo.objects.filter(id=staff_id).values(*temp_staff_key)
        staff_basic_data = list(staff_basic_data)
        staff_basic_data = staff_basic_data[0]

        # 将staff_work_data_list和customer_basic_data比对，如果相同则不变，若前者为1，后者为0，则+1，若前者为0，后者为1，则-1
        for i in staff_work_data_list:
            if staff_work_data_list[i] == customer_basic_data[i]:
                pass
            elif staff_work_data_list[i] == 1 and customer_basic_data[i] == 0:
                staff_basic_data[i + '_count'] += 1
            elif staff_work_data_list[i] == 0 and customer_basic_data[i] == 1:
                staff_basic_data[i + '_count'] -= 1
        print('staff_basic_data', staff_basic_data)
        # 将修改后的数据更新到员工表中
        judege_update = models.StaffInfo.objects.filter(id=staff_id).update(**staff_basic_data)

        if not judege_update:
            res['status'] = False
            res['message'] = '修改信息失败'
            return JsonResponse(res)
        judege_customer = models.CustomerList.objects.filter(id=customer_id).update(**customer_message[0])
        if not judege_customer:
            res['status'] = False
            res['message'] = '修改信息失败'
            return JsonResponse(res)
        return JsonResponse(res)
    else:
        res = {
            'status': False,
            'message': '请求方式错误'
        }
        return JsonResponse(res)


def customer_add(request):
    """添加数据"""
    res = {
        'status': True,
        'message': '数据添加成功'
    }
    if request.method == 'POST':
        customer_message = request.body.decode('utf-8')
        customer_message = eval(customer_message)
        customer_message = list(customer_message.values())

        user_num = request.tracer.user.get('id')
        user = models.StaffInfo.objects.filter(staff_num=user_num).first()

        # 修改里边的staff_id
        for i in customer_message:
            i['staff_id'] = user.id

        # 处理数据
        edit_clean(customer_message)

        # 获取staff_id
        staff_id = customer_message[0]['staff_id']

        # 客户数量+1
        models.StaffInfo.objects.filter(id=staff_id).update(customer_count=F('customer_count') + 1)
        staff_work_data_list = customer_message[0]
        judge_add = models.CustomerList.objects.create(**customer_message[0])
        # 添加数据
        # 处理数据，删除前六个字段
        staff_work_data_list.pop('oid')
        staff_work_data_list.pop('name')
        staff_work_data_list.pop('gender')
        staff_work_data_list.pop('deposit_amount')
        staff_work_data_list.pop('customer_relationship_type')
        staff_work_data_list.pop('customer_relationship_state_id')
        staff_work_data_list.pop('is_delete')
        staff_work_data_list.pop('staff_id')


        # 比对staff_work_data_list如果字段值为1，则将staff表中对应的数量字段加1
        for i in staff_work_data_list:
            if staff_work_data_list[i] == 1:
                i = i + '_count'
                models.StaffInfo.objects.filter(id=staff_id).update(**{i: F(i) + 1})

        if not judge_add:
            res['status'] = False
            res['message'] = '数据添加失败'
        return JsonResponse(res)
    else:
        res = {
            'status': False,
            'message': '请求方式错误'
        }
        return JsonResponse(res)


def principal_post(request):
    if request.method == 'GET':
        #获取get请求参数
        customer_id = request.GET
        print('customer_id',customer_id)
        user_num = request.tracer.user.get('id')
        print('user_num', user_num)
        # 获取登录者的用户id
        user_id = models.StaffInfo.objects.filter(staff_num=user_num).first().id
        print('user_id', user_id)
        # 获取登录者的用户级别
        user_level = models.StaffInfo.objects.filter(staff_num=user_num).first().level
        print('user_level', user_level)
        if user_level == 3:
            # 如果是管理员，就返回所有数据
            customer_data = models.CustomerList.objects.filter(is_delete=0).all().order_by('-staff__level').values()
        else:
            customer_data = models.CustomerList.objects.filter(is_delete=0, staff__staff_num=user_num).all().order_by(
                'id')

        customer_data = list(customer_data.values())
        # print('customer_data', customer_data)
        customer_list_clean(customer_data)

        customer_count = len(customer_data)

        # 获取资产量的选择
        deposit_amount_choice = models.CustomerList.deposit_amount_choice
        # 将deposit_amount_choice转换为[{'id': 1, 'name': '电话拒听的客户'},]
        deposit_amount_choice = [{'id': i[0], 'name': i[1]} for i in deposit_amount_choice]

        customer_relationship_type_choice = models.CustomerList.customer_relationship_type_choice

        # 将customer_relationship_type_choice转换为[{'id': 1, 'name': '电话拒听的客户'},]
        customer_relationship_type_choice = [{'id': i[0], 'name': i[1]} for i in customer_relationship_type_choice]

        customer_relationship_state_choice = models.RelationshipState.objects.all().order_by('id')
        customer_relationship_state_choice = list(customer_relationship_state_choice.values())

        staff_lis_choice = models.StaffInfo.objects.all().order_by('id')
        staff_lis_choice = list(staff_lis_choice.values())

        res_choice = {
            'deposit_amount_choice': deposit_amount_choice,
            'customer_relationship_type_choice': customer_relationship_type_choice,
            'customer_relationship_state_choice': customer_relationship_state_choice,
            'staff_lis_choice': staff_lis_choice
        }

        # print('customer_data', customer_data)
        return JsonResponse({'status': True, 'customer_data': customer_data, 'customer_count': customer_count,
                             'res_choice': res_choice, 'user_num': user_num})

